<template>
  <div class="tag-container">
    <el-card class="tag-card">
      <template #header>
        <div class="card-header">
          <span>标签管理</span>
          <el-button type="primary" @click="handleAddTag">添加标签</el-button>
        </div>
      </template>
      
      <!-- 标签筛选 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="标签分类">
            <el-select v-model="filterForm.category" placeholder="全部" clearable @change="handleFilter">
              <el-option
                v-for="category in categories"
                :key="category"
                :label="category"
                :value="category"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称">
            <el-input v-model="filterForm.name" placeholder="输入标签名称" clearable @keyup.enter="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 标签表格 -->
      <el-table :data="filteredTags" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="标签名称" min-width="120" />
        <el-table-column prop="category" label="标签分类" width="120" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="使用次数" width="100">
          <template #default="scope">
            <span>{{ getTagUsageCount(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEditTag(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDeleteTag(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTags.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑标签对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加标签' : '编辑标签'"
      width="500px"
    >
      <el-form :model="tagForm" :rules="rules" ref="tagFormRef" label-width="100px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" />
        </el-form-item>
        <el-form-item label="标签分类" prop="category">
          <el-select v-model="tagForm.category" filterable allow-create default-first-option placeholder="选择或创建分类">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="tagForm.description" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAllTags, createTag, updateTag, deleteTag, getTagsByCategory } from '@/api/tag';

export default {
  name: 'TagManagement',
  setup() {
    const loading = ref(false);
    const tags = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const dialogVisible = ref(false);
    const dialogType = ref('add'); // 'add' 或 'edit'
    const tagFormRef = ref(null);

    // 表单数据
    const tagForm = reactive({
      id: null,
      name: '',
      category: '',
      description: ''
    });

    // 筛选表单
    const filterForm = reactive({
      name: '',
      category: ''
    });

    // 校验规则
    const rules = {
      name: [
        { required: true, message: '请输入标签名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在1到50个字符之间', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择或创建标签分类', trigger: 'change' }
      ]
    };

    // 获取所有标签
    const fetchTags = async () => {
      loading.value = true;
      try {
        const res = await getAllTags();
        tags.value = res;
      } catch (error) {
        console.error('获取标签列表失败:', error);
        ElMessage.error('获取标签列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 根据分类获取标签
    const fetchTagsByCategory = async (category) => {
      loading.value = true;
      try {
        const res = await getTagsByCategory(category);
        tags.value = res;
      } catch (error) {
        console.error('获取标签列表失败:', error);
        ElMessage.error('获取标签列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 所有标签分类
    const categories = computed(() => {
      const categorySet = new Set(tags.value.map(tag => tag.category).filter(Boolean));
      return Array.from(categorySet);
    });

    // 筛选后的标签
    const filteredTags = computed(() => {
      return tags.value.filter(tag => {
        const nameMatch = !filterForm.name || tag.name.toLowerCase().includes(filterForm.name.toLowerCase());
        const categoryMatch = !filterForm.category || tag.category === filterForm.category;
        return nameMatch && categoryMatch;
      });
    });

    // 分页数据
    const paginatedTags = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return filteredTags.value.slice(startIndex, startIndex + pageSize.value);
    });

    // 获取标签使用次数
    const getTagUsageCount = (tag) => {
      return tag.funds ? tag.funds.length : 0;
    };

    // 筛选
    const handleFilter = () => {
      if (filterForm.category && !filterForm.name) {
        fetchTagsByCategory(filterForm.category);
      } else {
        currentPage.value = 1;
      }
    };

    // 重置筛选
    const resetFilter = () => {
      filterForm.name = '';
      filterForm.category = '';
      fetchTags();
    };

    // 添加标签
    const handleAddTag = () => {
      dialogType.value = 'add';
      resetForm();
      dialogVisible.value = true;
    };

    // 编辑标签
    const handleEditTag = (row) => {
      dialogType.value = 'edit';
      Object.assign(tagForm, row);
      dialogVisible.value = true;
    };

    // 删除标签
    const handleDeleteTag = (row) => {
      ElMessageBox.confirm(
        `确定要删除标签 "${row.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          await deleteTag(row.id);
          ElMessage.success('删除成功');
          fetchTags();
        } catch (error) {
          console.error('删除标签失败:', error);
          ElMessage.error('删除标签失败');
        }
      }).catch(() => {});
    };

    // 提交表单
    const submitForm = async () => {
      if (!tagFormRef.value) return;
      
      await tagFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              await createTag(tagForm);
              ElMessage.success('添加成功');
            } else {
              await updateTag(tagForm.id, tagForm);
              ElMessage.success('更新成功');
            }
            dialogVisible.value = false;
            fetchTags();
          } catch (error) {
            console.error(dialogType.value === 'add' ? '添加标签失败:' : '更新标签失败:', error);
            ElMessage.error(dialogType.value === 'add' ? '添加标签失败' : '更新标签失败');
          }
        } else {
          ElMessage.error('请完善表单信息');
          return false;
        }
      });
    };

    // 重置表单
    const resetForm = () => {
      if (tagFormRef.value) {
        tagFormRef.value.resetFields();
      }
      Object.assign(tagForm, {
        id: null,
        name: '',
        category: '',
        description: ''
      });
    };

    // 分页
    const handleSizeChange = (size) => {
      pageSize.value = size;
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    onMounted(() => {
      fetchTags();
    });

    return {
      loading,
      tags,
      currentPage,
      pageSize,
      dialogVisible,
      dialogType,
      tagFormRef,
      tagForm,
      filterForm,
      rules,
      categories,
      filteredTags,
      paginatedTags,
      fetchTags,
      handleFilter,
      resetFilter,
      handleAddTag,
      handleEditTag,
      handleDeleteTag,
      submitForm,
      resetForm,
      getTagUsageCount,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.tag-container {
  padding: 20px;
}

.tag-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 